"""Used to import files into the TMS program"""
import Tms

def importFromCSV(fromFile):
    """ imports a file from a csv file and returns list"""
    import csv
    importCsv = open(fromFile, 'rt')
    reader = csv.DictReader(importCsv)
    newFile = []
    for row in reader:
        newFile.append(row)
    importCsv.close()
    return newFile

def convertYear(date):
    mo,day,yr = date.split('/')
    if len(yr) == 2:
        yr = '20' + yr
    return mo + '/' + day + '/' + yr

def convertCSV2Sqlite(fromFile):
    """ import csv file and save to sqlite """
    csvData = importFromCSV(fromFile)
    return csvData

def saveToCsv(toFile, data, fieldnames):
    """ Save to CSV file format """
    import csv
    f  =  open(toFile,  'wt')
    writer  =  csv.DictWriter(f,  fieldnames=fieldnames, dialect='excel', quoting=csv.QUOTE_NONNUMERIC)
    #print writer.dialect
    headers  =  {}
    for  n  in  fieldnames:
        headers[n]  =  n
    writer.writerow(headers)
    for  i  in  data:
        writer.writerow(i)

def importCalendarFromTMSExplorer():
    """ Import calendar.csv file from tms explorer program
    calendar.csv should be in the same directory as the tms program"""
    schedule = importFromCSV('Calendar.csv')
    newSchedule = []
    fieldnames = ('Date','Review', 'H Source', '1 Source', '2 Source', '2 Theme', '3 Source', '3 Theme', '3 Bro Only')
    for week in schedule:
        date = convertYear(week['Date'])
        new = {'Date':date, 'Review':week['Review'], 'H Source':week['H_Source'], '1 Source':week['1_Source'], '2 Source':week['2_Source'], '2 Theme':week['2_Theme'], '3 Source':week['3_Source'], '3 Theme':week['3_Theme'], '3 Bro Only':week['#3 Brother Only']}
        newSchedule.append(new)
    saveToCsv('2009Schedule.csv', newSchedule, fieldnames)
    print newSchedule
        
if __name__ == '__main__':
    Tms.Main()
    